package com.qianniu.napi.admin.web;

import akka.actor.ActorRef;
import akka.actor.Props;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.google.common.base.Strings;
import com.qianniu.napi.admin.entity.*;
import com.qianniu.napi.admin.service.IGoodsService;
import com.qianniu.napi.admin.service.INewsCategoryService;
import com.qianniu.napi.admin.service.INewsService;
import com.qianniu.napi.admin.service.IResourceService;
import com.qianniu.napi.admin.service.akka.AkkaServer;
import com.qianniu.napi.admin.service.akka.ResourceActor;
import com.qianniu.napi.admin.service.akka.StoreActor;
import com.qianniu.napi.common.config.Constants;
import com.qianniu.napi.common.util.ObjectUtil;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.validation.Valid;
import java.util.*;

/**
 * <p>
 * 新闻内容
 * </p>
 *
 * @author chenxuebin
 * @since 2018-07-29
 */
@Controller
public class NewsController {

    private static final Logger logger = LoggerFactory.getLogger(NewsController.class);

    @Autowired
    private INewsService newsService;
    @Autowired
    private IResourceService resourceService;

    @Autowired
    private INewsCategoryService newsCategoryService;

    @Autowired
    private IGoodsService goodsService;

    @RequiresPermissions("admin:user:view")
    @RequestMapping("admin/news/index")
    public String index(Model model) {
        List<NewsCategory> nlist = newsCategoryService.selectList(new EntityWrapper<NewsCategory>()
                .setSqlSelect("name,id")
                .eq("mpid", ObjectUtil.getMpid())
        );
        model.addAttribute("nlist", nlist);

        Integer about = newsService.selectCount(new EntityWrapper<News>()
                .setSqlSelect("name,id")
                .eq("mpid", ObjectUtil.getMpid())
                .eq("cid", -10)
        );// 关于我们
        Integer team = newsService.selectCount(new EntityWrapper<News>()
                .setSqlSelect("name,id")
                .eq("mpid", ObjectUtil.getMpid())
                .eq("cid", -20)
        );// 关于我们

        model.addAttribute("about", about);
        model.addAttribute("team", team);
        model.addAttribute("nlist", nlist);
        return "admin/news";
    }

    @RequiresPermissions("admin:user:view")
    @RequestMapping("/admin/news/list")
    @ResponseBody
    public Page<News> alist(@RequestParam(value = "offset", required = false) Integer offset,
                            @RequestParam(value = "status", required = false) Integer status,
                            @RequestParam(value = "search", required = false) String search,
                            @RequestParam(value = "cid", required = false) Integer cid,
                            @RequestParam(value = "ncategory", required = false) Integer ncategory,
                            @RequestParam(value = "limit", required = false) Integer limit) {

        Wrapper<News> wrapper = new EntityWrapper<News>();
        int utype = ObjectUtil.getUserType();
        if (utype < 39)
            wrapper.eq("mpid", ObjectUtil.getMpid());
        else if (utype < 99)
            wrapper.eq("mid", ObjectUtil.getMid());
//        wrapper.eq("state", 1);
        if (!Strings.isNullOrEmpty(search))
            wrapper.andNew().like("title", search).or().like("info", search);

        if (ncategory != null && ncategory != 0) wrapper.eq("cid", ncategory);
        if (cid != null && cid != 0) wrapper.eq("cid", ncategory);
//        else wrapper.gt("cid", 0);

        wrapper.orderBy("id", false);
        Page<News> page = newsService.selectPage(new Page<News>(offset / limit + 1, limit), wrapper);
        if(page.getRecords().size()>0){
            Map<String,String> map = new HashMap<String,String>();

            List<NewsCategory> nlist = newsCategoryService.selectList(new EntityWrapper<NewsCategory>()
                    .setSqlSelect("name,id")
                    .eq("mpid", ObjectUtil.getMpid())
            );
            for(NewsCategory nc:nlist){
                map.put(nc.getId().toString(),nc.getName());
            }
            map.put("-10","关于我们");
            map.put("-20","团队介绍");


            for(News item:page.getRecords()){
                item.setCname(map.get(item.getCid().toString()));
            }
        }
        return page;
    }

    @RequestMapping("/admin/news/add")
    public String add(@Valid News bean, BindingResult bindingResult, Model model) {
        // 字段校验
        if (bindingResult.hasErrors()) {
            logger.debug("There are errors! {}", bindingResult);
            return null;
        }
        bean.setCreatetime(new Date());
        bean.setState(1);

        String neirong = bean.getInfo().replaceAll("小分店", "仟牛通");
        bean.setInfo(neirong);

        bean.setMid(ObjectUtil.getMid());
        bean.setMpid(ObjectUtil.getMpid());
        bean.setUid(ObjectUtil.getUid());
        if(!Strings.isNullOrEmpty(bean.getVurl())){
            Resource resource = resourceService.selectOne(new EntityWrapper<Resource>()
                    .eq("pic",bean.getVurl()));
            if(resource!=null) bean.setVheight(resource.getMheight());
            if(resource!=null) bean.setVpixel(resource.getPixel());
        }

        Random ran = new Random();
        if (bean.getCid().intValue() == 24) {
            bean.setViews(ran.nextInt(3000) + 2000);
        }
        bean.insert();
        //更新资源文件
        AkkaServer.system.actorOf(Props.create(ResourceActor.class))
                .tell("News@"+bean.getId()+"@insert", ActorRef.noSender());

        AkkaServer.system.actorOf(Props.create(StoreActor.class))
                .tell(Constants.AKKA_MSG_NEWS_MODIFY + "@" + bean.getId(), ActorRef.noSender());

        List<NewsCategory> nlist = newsCategoryService.selectList(new EntityWrapper<NewsCategory>()
                .setSqlSelect("name,id")
                .eq("mpid", ObjectUtil.getMpid())
                .eq("state", 1)
        );
        model.addAttribute("nlist", nlist);
        return "admin/news";
    }

    @RequestMapping("/admin/news/getNewsById")
    @ResponseBody
    public News getNewsById(long id) {
        News news = newsService.selectById(id);
        return news;
    }

    @RequestMapping("/admin/news/deleteOne")
    @ResponseBody
    public int deleteOne(long id) {
        boolean isSucc = newsService.deleteById(id);
        return isSucc ? 1 : 0;
    }

    @RequestMapping("/admin/news/changeState")
    @ResponseBody
    public String changeState(long id, int state) {
        News bean = new News();
        bean.setId(id);
        bean.setState(state);
        bean.setModifytime(new Date());
        bean.setModifier(ObjectUtil.getUid());
        newsService.updateById(bean);
        return "success";
    }

    @RequestMapping("/admin/news/modify")
    public String update(News bean) {
        bean.setModifytime(new Date());
        bean.setModifier(ObjectUtil.getUid());

        News dbnews = newsService.selectById(bean.getId());
        if(!Strings.isNullOrEmpty(bean.getVurl())&&(Strings.isNullOrEmpty(dbnews.getVurl())||!dbnews.getVurl().equals(bean.getVurl()))){
            Resource resource = resourceService.selectOne(new EntityWrapper<Resource>()
                    .eq("pic",bean.getVurl()));
            if(resource!=null) bean.setVheight(resource.getMheight());
            if(resource!=null) bean.setVpixel(resource.getPixel());
        }

        boolean isSuccc = newsService.updateById(bean);
        AkkaServer.system.actorOf(Props.create(StoreActor.class))
                .tell(Constants.AKKA_MSG_NEWS_MODIFY + "@" + bean.getId(), ActorRef.noSender());
        //更新资源文件
        AkkaServer.system.actorOf(Props.create(ResourceActor.class))
                .tell("News@"+bean.getId()+"@update", ActorRef.noSender());

        if (isSuccc) {
            return "redirect:index";
        }
        return "error";
    }

    @RequestMapping("/admin/news/getStoreGoods")
    @ResponseBody
    public Jinfo getStoreGoods(Long sid) {
        Long mpid = ObjectUtil.getMpid();

        Wrapper<Goods> wrapper = new EntityWrapper<Goods>().setSqlSelect("id,name").eq("mpid", mpid);
        wrapper.ge("type",0).eq("state",1)
                .eq("status",2);

        if (sid != null && sid.longValue() > 0) wrapper.eq("sid", sid);

        List<Goods> list = goodsService.selectList(wrapper);
        Jinfo info = new Jinfo();
        info.setData(list);
        return info;
    }

    @RequestMapping("/admin/news/guanliansp")
    @ResponseBody
    public Jinfo guanliansp(News bean) {
        bean.setModifytime(new Date());
        bean.setModifier(ObjectUtil.getUid());
        Goods goods = goodsService.selectOne(new EntityWrapper<Goods>()
                .setSqlSelect("id,name,type").eq("id",bean.getGid()));
        bean.setGname(goods.getName());
        bean.setGtype(goods.getType());

        boolean isSuccc = newsService.updateById(bean);

        Jinfo info = new Jinfo();
        if (isSuccc) {
            return info;
        }
        info.setCode(1);
        return info;
    }

}
